package cn.boysoft.core.util;

import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.text.SimpleDateFormat;
import java.util.LinkedHashSet;
import java.util.Set;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import cn.boysoft.module.security.model.entity.ResourceEntity;
import cn.boysoft.module.security.model.entity.ResourceTypeEnum;

import com.fasterxml.jackson.dataformat.xml.XmlMapper;

public class XmlUtil {
	public static String toXml(Object target){
		 XmlMapper objectMapper =  new XmlMapper();
		 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");  
		 objectMapper.setDateFormat(format); 
		 StringWriter stringWriter = new StringWriter();
		 try {
			objectMapper.writeValue(stringWriter, target);
		} catch (Exception e) {
			e.printStackTrace();
		}
		return stringWriter.toString();
	}

	public static String formatXml(String targetStr) {
		try{
			SAXReader reader = new SAXReader();
			StringReader in = new StringReader(targetStr);
			Document doc =  reader.read(in);
			OutputFormat formater = OutputFormat.createPrettyPrint();
			formater.setEncoding("utf-8");
			StringWriter out = new StringWriter();
			XMLWriter writer = new XMLWriter(out, formater);
			writer.write(doc);
			return out.toString();
		}catch(Exception e){
			return targetStr;
		}
		
	}
	
	
	
	
	
	public static void main(String[] args) throws IOException, SecurityException, IllegalArgumentException, NoSuchFieldException, IllegalAccessException{
		
		
       
		
		ResourceEntity root = new ResourceEntity();
		Set<ResourceEntity> rootChildren = new LinkedHashSet<ResourceEntity>();
		root.setChildren(rootChildren);
		
		ResourceEntity resourceEntity = new ResourceEntity();
		rootChildren.add(resourceEntity);
		
		resourceEntity.setName("安全管理");
		resourceEntity.setId("01_02");
		resourceEntity.setResourceType(ResourceTypeEnum.MENU);
		Set<ResourceEntity> children = new LinkedHashSet<ResourceEntity>();
		resourceEntity.setChildren(children);
		
		resourceEntity = new ResourceEntity();
		resourceEntity.setName("用户管理");
		resourceEntity.setId("01_02_02");
		resourceEntity.setResourceType(ResourceTypeEnum.MENU);
		children.add(resourceEntity);
		
		resourceEntity = new ResourceEntity();
		resourceEntity.setName("角色管理");
		resourceEntity.setResourceType(ResourceTypeEnum.MENU);
		resourceEntity.setId("01_02_03");
		children.add(resourceEntity);
		
		resourceEntity = new ResourceEntity();
		resourceEntity.setName("资源管理");
		resourceEntity.setId("01_02_03");
		resourceEntity.setResourceType(ResourceTypeEnum.MENU);
		children.add(resourceEntity);
		System.out.print(toXml(root));
	}
}
